package org.dromara.yuanshidian.interest;



import cn.hutool.core.date.DateUtil;
import lombok.Data;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Data
public class InterestCalcLocal {
    //计息节点
    Date calcPeriod;
   //年利率Map
    Map<Integer, Double> rateMap;
   //结果集
    Map<Integer, Double> resultMap;
    public void initInterestcalcLocal(Date calcPeriod, Map<Integer, Double> rateMap) {
        this.calcPeriod = calcPeriod;
        this.rateMap = rateMap;
        resultMap = new HashMap<>();
    }

    /**
     * 计算周期
     */
    public long getInterestPeriod(Date period, int year) {
        int startYear = DateUtil.year(period);
        int endYear = DateUtil.year(calcPeriod);
        //判断是否为同一年
        if (startYear - endYear == 0) {
            return 1 + DateUtil.betweenMonth(period, calcPeriod, false);
        } else if(year - startYear == 0) {
            Date endOfYear = DateUtil.endOfYear(period);// 获取当年最后一天:如2021-12-31
            return 1 + DateUtil.betweenMonth(period, endOfYear,  false);
        }else {
            return 12;
        }
    }
    /**
     * 月息
     */
    public Double calcMonthInterest(Double amount,int year){
        Double rate = rateMap.get(year);
        return  amount * rate / 12;

    }
    /**
     * 年息
     */
    public Double caclYearInterest(Double amount,int year,Date period){
        double res = calcMonthInterest(amount,year)*getInterestPeriod(period,year);
        resultMap.compute(year,(k,v) -> v ==null ? res :v +res);
        return res;
    }
}
